package com.ruyuan2020.furnishing.member.service.impl;

import com.ruyuan2020.common.exception.BusinessException;
import com.ruyuan2020.furnishing.account.api.AccountApi;
import com.ruyuan2020.furnishing.account.domain.AccountDTO;
import com.ruyuan2020.furnishing.member.constant.MemberConstants;
import com.ruyuan2020.furnishing.member.dao.MemberCompanyDAO;
import com.ruyuan2020.furnishing.member.dao.MemberDAO;
import com.ruyuan2020.furnishing.member.domain.*;
import com.ruyuan2020.furnishing.member.service.MemberService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDAO memberDAO;

    @Autowired
    private MemberCompanyDAO memberCompanyDAO;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @DubboReference(version = "1.0.0", cluster = "failfast")
    private AccountApi accountApi;

    /**
     * 创建会员
     *
     * @param memberDTO 会员信息
     */
    @Override
    @Transactional
    public Long save(MemberDTO memberDTO) {
//        long count = memberDAO.countByUsername(memberDTO.getUsername());
//        if (count > 0) throw new BusinessException("用户名已存在");
        // 加密密码影响性能
        memberDTO.setPassword(passwordEncoder.encode(memberDTO.getPassword()));
        Long id = memberDAO.save(memberDTO.clone(MemberDO.class));
        // 会员类型是公司，创建公司信息
        if (MemberConstants.TYPE_COMPANY.equals(memberDTO.getType())) {
            MemberCompanyDO memberCompanyDO = new MemberCompanyDO();
            memberCompanyDO.setMemberId(id);
            memberCompanyDAO.save(memberCompanyDO);
        }
        // 创建会员账户信息
        AccountDTO accountDTO = new AccountDTO();
        accountDTO.setMemberId(id);
        accountApi.createAccount(accountDTO);
        return id;
    }

    /**
     * 获取会员信息
     *
     * @param memberId 会员id
     * @return 会员信息
     */
    @Override
    public MemberDTO getMember(Long memberId) {
        MemberDTO memberDTO = memberDAO.getMemberById(memberId).map(it -> it.clone(MemberDTO.class)).orElseThrow(() -> new BusinessException("会员不存在"));
        memberDTO.setPassword(null);
        memberDTO.setId(memberId);
        return memberDTO;
    }

    @Override
    public MemberDTO getByUsername(String username) {
        return memberDAO.getByUsername(username).map(it -> it.clone(MemberDTO.class)).orElseThrow(() -> new BusinessException("会员不存在"));
    }
}
